// Copyright © 2023 Cisco Systems, Inc. and its affiliates.
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package findingkey

import (
	"crypto/sha256"
	"fmt"

	apitypes "github.com/openclarity/openclarity/api/types"
)

type ExploitKey struct {
	SourceDB string
	CveID    string
	Urls     *[]string
}

// String returns an unique string representation of the exploit finding.
func (k ExploitKey) String() string {
	hash := sha256.New()
	for _, url := range *k.Urls {
		hash.Write([]byte(url))
	}

	return fmt.Sprintf("%s.%s.%s", k.SourceDB, k.CveID, string(hash.Sum(nil)))
}

// ExploitString returns an unique string representation of the exploit independent of
// where the exploit finding was found by the scanner.
func (k ExploitKey) ExploitString() string {
	return k.String()
}

// Filter returns a string that can be used to filter the exploit finding in the database.
func (k ExploitKey) Filter() string {
	return fmt.Sprintf(
		"findingInfo/sourceDB eq '%s' and findingInfo/cveID eq '%s' and findingInfo/urls eq '%s'",
		k.SourceDB, k.CveID, *k.Urls,
	)
}

func GenerateExploitKey(exploit apitypes.ExploitFindingInfo) ExploitKey {
	return ExploitKey{
		SourceDB: *exploit.SourceDB,
		CveID:    *exploit.CveID,
		Urls:     exploit.Urls,
	}
}
